﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace ProgrammersCalculator.Convertor
{
    public class NumberSystemConverter : IValueConverter
    {
        Stack<object> stack = new Stack<object>();
        public object Convert(object value, Type targetType, object parameter,
                     CultureInfo culture)
        {
            // Store result digits in array
            object[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F" };
            try
            {
                // Get the source value
                int number = System.Convert.ToInt32(value.ToString());
                if (number == 0)
                {
                    return 0;
                }
                // Get the target number system
                int divisor = System.Convert.ToInt32(parameter.ToString());
                while (number > 0)
                {
                    int remainder = number % divisor;
                    // Push digits to stack
                    stack.Push(digits[remainder]);
                    number /= divisor;
                }
                StringBuilder builder = new StringBuilder();
                while (stack.Count > 0)
                {
                    builder.Append(stack.Pop().ToString());
                    // Return digits in LIFO order
                }
                return builder.ToString();
                // Return result
            }
            catch (Exception)
            {
                return null;
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter,
                      CultureInfo culture)
        {
            return null;
        }
    }
}
